/*
 * @Author: Zhouhai 497675647@qq.com
 * @Date: 2023-03-03 10:52:16
 * @LastEditors: Zhouhai 497675647@qq.com
 * @LastEditTime: 2023-03-03 17:04:34
 */
import Taro from '@tarojs/taro';
import { action, makeAutoObservable, observable } from 'mobx';
import constant from '@/servers/constant';
import { LoginInfo } from '../type.d/login';
import { getInfo, login } from '@/api/login';
import getBaseUrl from '@/servers/baseUrl';



class UserStore {
    token: string = Taro.getStorageSync(constant.token)
    name: string = Taro.getStorageSync(constant.name)
    avatar: string = Taro.getStorageSync(constant.avatar)
    roles: string[] = Taro.getStorageSync(constant.roles)
    permissions: string[] = Taro.getStorageSync(constant.permissions)
	constructor() {
		makeAutoObservable(this,{
            token: observable,
            name: observable,
            avatar: observable,
            roles: observable,
            permissions: observable,
            SET_TOKEN: action,
            SET_AVATAR: action,
            SET_ROLES: action,
            SET_NAME: action,
            SET_PERMISSIONS: action,
        });
	}



    SET_TOKEN = (token: string) =>{
        Taro.setStorageSync(constant.token, token);
       this.token = token
    }

    SET_NAME = (name: string) =>{
        Taro.setStorageSync(constant.name, name);
        this.name = name
    }

    SET_AVATAR = (avatar: string) =>{
        Taro.setStorageSync(constant.avatar, avatar);
        this.avatar = avatar
    }

    SET_ROLES = (roles: string[]) =>{
        Taro.setStorageSync(constant.roles, roles);
        this.roles = roles
    }

    SET_PERMISSIONS = (permissions: string[]) =>{
        Taro.setStorageSync(constant.permissions, permissions);
        this.permissions = permissions
    }

    login = async (loginInfo: LoginInfo): Promise<boolean> => {
		return login(loginInfo)
			.then((res: any) => {
				this.SET_TOKEN(res.token);
				return true;
			})
			.catch(() => {
                this.SET_TOKEN('');
				return false;
			});
	};

    GetInfo = async (): Promise<any> => {
		return new Promise((resolve, reject) => {
			getInfo()
				.then((res: any) => {
					let user = res.user;
					if (res.roles && res.roles.length > 0) {
						// 验证返回的roles是否是一个非空数组
						this.SET_ROLES(res.roles);
						this.SET_PERMISSIONS(res.permissions);
					} else {
                        this.SET_ROLES(['ROLE_DEFAULT']);
					}
					this.SET_NAME(user.userName || '');
                    const avatar = (user.avatar === '' || user.avatar == null)
						? require('@/resource/images/profile.jpg')
						: getBaseUrl('') + user.avatar;
					this.SET_AVATAR(avatar);
					resolve(res);
				})
				.catch((error) => {
					reject(error);
				});
		});
	};


}
export {UserStore};